//
//  LoginViewController.m
//  PYWGetColor
//
//  Created by ENERGY on 2018/5/31.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "LoginViewController.h"
#import "JPUSHService.h"
#import "RegisterViewController.h"
#import "ForgetPwddViewController.h"
#import "WXSQLoginViewController.h"
#import "AppDelegate.h"
#import <UMSocialCore/UMSocialCore.h>

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITextField * phoneNumTextField; // 手机号
@property (nonatomic, strong)UITextField * codeTextField; // 密码

@property (nonatomic, strong) NSString *openId;// 微信openId
@property (nonatomic, strong) NSString *nickname;// 微信昵称
@property (nonatomic, strong) NSString *sex;// 性别
@property (nonatomic, strong) NSString *headimgurl;// 头像
@property (nonatomic, strong) NSString *mobile;// 绑定手机号
//@property (nonatomic, strong) NSString *equip;// 设备号
@end

@implementation LoginViewController

- (void)PostLogin {
    NSString *telephoneStr = self.phoneNumTextField.text;
    NSString *pwdStr = self.codeTextField.text;
    if (telephoneStr.length <= 0 || telephoneStr == nil || telephoneStr == NULL) {
        ShowMessage(@"请输入手机号");
        return;
    }
    if ([pwdStr isEqualToString:@""] || [pwdStr isKindOfClass:NULL] || [pwdStr isKindOfClass:nil]) {
        ShowMessage(@"请输入密码");
        return;
    }
//    [UserModel sharedInstanced].jpushRegistrationID = registrationID;
    NSString *passwordStr = [self md5:pwdStr];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=login" parameters:@{@"username":telephoneStr,@"password":passwordStr,@"equip":[UserModel sharedInstanced].jpushRegistrationID} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            ShowMessage(@"登录成功");
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            [appDelegate loginStateChange];
            [UserModel sharedInstanced].token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"token"]];
            [UserModel sharedInstanced].userId = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"uid"]];
            [UserModel sharedInstanced].mobile = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"username"]];
            
            EMError *error2 = [[EMClient sharedClient] loginWithUsername:telephoneStr password:telephoneStr];
            if (!error2) {
                NSLog(@"登录成功");
                [[EMClient sharedClient].options setIsAutoLogin:YES];// 自动登录
            }
            PYWLaunchTool *pywlaTool = [[PYWLaunchTool alloc]init];
            [pywlaTool registerPushBieMing];// 极光别名注册  和后台上传别名   踢出登录账号
        }else{
            ShowMessage(@"用户名或密码错误");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
- (void)isRegisterWithTele{ // 微信授权登录前 校验是否注册过 （如果没有 需要先绑定过手机号）
    [self showprogressHUD];
    PYWLaunchTool *pywlaTool = [[PYWLaunchTool alloc]init];
    [pywlaTool registerPushBieMing];// 极光别名注册  和后台上传别名   踢出登录账号
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=isWxLogin" parameters:@{@"openId":self.openId,@"equip":[UserModel sharedInstanced].jpushRegistrationID} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) { // 已注册过 直接微信授权登录
            ShowMessage(responseObject[@"message"]);
            NSString *telephoneStr = [UserModel sharedInstanced].mobile;
            EMError *error2 = [[EMClient sharedClient] loginWithUsername:telephoneStr password:telephoneStr];
            if (!error2) {
                NSLog(@"登录成功");
                [[EMClient sharedClient].options setIsAutoLogin:YES];// 自动登录
            }
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            [appDelegate loginStateChange];
            [UserModel sharedInstanced].userId = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"uid"]];
            [UserModel sharedInstanced].token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"token"]];
            
            PYWLaunchTool *pywla = [[PYWLaunchTool alloc]init];
            [pywla jspushRegisterToServers:[UserModel sharedInstanced].jpushRegistrationID]; // 设备别名给后台 判断是否发送极光自定义消息  如果发送代表其他设备登录  提出其他设备登录状态
        }else{ // 未注册
            ShowMessage(@"第一次微信登录,请先绑定手机号");
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                WXSQLoginViewController *VC = [[WXSQLoginViewController alloc]init];
                VC.openId = self.openId;
                VC.nickname = self.nickname;
                VC.sex = [self.nickname isEqualToString:@"男"]?@"1":@"2";
                VC.headimgurl = self.headimgurl;
//                VC.equip = self.equip;
                [self.navigationController pushViewController:VC animated:YES];
            });
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        //        [self postAuthoRegistered];
        //        [self showError:error];
    }];
}
#pragma mark - 第三方登录授权
// 微信授权登录
- (void)getAuthWithUserInfoFromWechat
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            //            SendAuthResp
            // 授权信息
            NSLog(@"Wechat uid: %@", resp.uid);
            NSLog(@"Wechat openid: %@", resp.openid);
            NSLog(@"Wechat unionid: %@", resp.unionId);// 微信唯一标识
            NSLog(@"Wechat accessToken: %@", resp.accessToken);
            NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
            NSLog(@"Wechat expiration: %@", resp.expiration);
            
            // 用户信息
            NSLog(@"Wechat name: %@", resp.name);
            NSLog(@"Wechat iconurl: %@", resp.iconurl);
            NSLog(@"Wechat gender: %@", resp.unionGender);
            
            // 第三方平台SDK源数据
            NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
            self.openId = resp.openid;
            self.nickname = resp.name;
            self.sex = resp.unionGender;
            self.headimgurl = resp.iconurl;
//            self.equip = resp.uid;
            
            [self isRegisterWithTele];
        }
    }];
}
#pragma mark - action
- (void)loginBtnClick:(UIButton *)sender{
    NSLog(@"登录");
    
    
    [self PostLogin];
}
// 极光推送 标签和别名设置成功回调
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}
- (void)forgetBtnClick:(UIButton *)sender{
    NSLog(@"忘记密码");
    ForgetPwddViewController *VC = [[ForgetPwddViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)registerBtnClick:(UIButton *)sender{
    NSLog(@"快速注册");
    RegisterViewController *VC = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    self.navigationController.navigationBar.hidden = NO;
    //控件初始化
    [self setUpUI];
}
- (void)imagesViewTap:(UITapGestureRecognizer *)tapgesture
{
    [self getAuthWithUserInfoFromWechat];
}
- (void)setUpUI{
    //手机图标
    UIImageView * phoneImageView = [[UIImageView alloc] init];
    phoneImageView.image = [UIImage imageNamed:@"logo_ico.1"];
    [self.view addSubview:phoneImageView];
    //手机textfield
    self.phoneNumTextField = [[UITextField alloc] init];
    self.phoneNumTextField.placeholder = @"手机号";
    self.phoneNumTextField.font = DEF_FontSize_14;
    [self.view addSubview:self.phoneNumTextField];
    //手机号下line
    UIView * phoneLineView = [[UIView alloc] init];
    phoneLineView.backgroundColor = getColor(@"e9e9e9");
    [self.view addSubview:phoneLineView];
    //密码图标
    UIImageView * codeImageView = [[UIImageView alloc] init];
    codeImageView.image = [UIImage imageNamed:@"logo_ico.2"];
    [self.view addSubview:codeImageView];
    //密码textfield
    self.codeTextField = [[UITextField alloc] init];
    self.codeTextField.secureTextEntry = YES;
    self.codeTextField.placeholder = @"输入密码";
    self.codeTextField.font = DEF_FontSize_14;
    [self.view addSubview:self.codeTextField];
    //密码下line
    UIView * codeLineView = [[UIView alloc] init];
    codeLineView.backgroundColor = getColor(@"e9e9e9");
    [self.view addSubview:codeLineView];
    //登录按钮
    UIButton * loginBtn = [[UIButton alloc] init];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = DEF_FontSize_14;
    loginBtn.layer.masksToBounds = YES;
    loginBtn.layer.cornerRadius = 4;
    [loginBtn setBackgroundColor:getColor(@"3eceb2")];
    [loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    //忘记密码
    UIButton * forgetBtn = [[UIButton alloc] init];
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    forgetBtn.titleLabel.font = DEF_FontSize_13;
    [forgetBtn setBackgroundColor:[UIColor clearColor]];
    [forgetBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(forgetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetBtn];
    //快速注册
    UIButton * registerBtn = [[UIButton alloc] init];
    [registerBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    registerBtn.titleLabel.font = DEF_FontSize_13;
    [registerBtn setBackgroundColor:[UIColor clearColor]];
    [registerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    //第三方登录横线
    UIView * otherLogLineView = [[UIView alloc] init];
    otherLogLineView.backgroundColor = getColor(@"e9e9e9");
    [self.view addSubview:otherLogLineView];
    //第三方登录标题
    UILabel * otherLogLab = [[UILabel alloc] init];
    otherLogLab.text = @"第三方登录";
    otherLogLab.font = DEF_FontSize_13;
    otherLogLab.textColor = getColor(@"e9e9e9");
    otherLogLab.textAlignment = NSTextAlignmentCenter;
    otherLogLab.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:otherLogLab];
    //微信图标
    UIImageView * weChatImageView = [[UIImageView alloc] init];
    weChatImageView.image = [UIImage imageNamed:@"logo_btn.1"];
    weChatImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * imagesViewTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imagesViewTap:)];
    [weChatImageView addGestureRecognizer:imagesViewTapGestureRecognizer];
    [self.view addSubview:weChatImageView];
    //微信标题
    UILabel * weChatLab = [[UILabel alloc] init];
    weChatLab.text = @"微信";
    weChatLab.font = DEF_FontSize_13;
    weChatLab.textColor = getColor(@"e9e9e9");
    weChatLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:weChatLab];
    
    __weak typeof (self)weakSelf = self;
    //手机图标
    [phoneImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15/WIDTH_5S_SCALE);
        make.top.mas_equalTo(55/WIDTH_5S_SCALE);
        make.width.mas_equalTo(11/WIDTH_5S_SCALE);
        make.height.mas_equalTo(15/WIDTH_5S_SCALE);
    }];
    //手机输入框
    [self.phoneNumTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneImageView).mas_offset(15/WIDTH_5S_SCALE);
        make.right.equalTo(weakSelf.view).mas_offset(-15/WIDTH_5S_SCALE);
        make.height.mas_offset(20/WIDTH_5S_SCALE);
        make.centerY.equalTo(phoneImageView.mas_centerY);
    }];
    //手机下横线
    [phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneNumTextField.mas_bottom).mas_offset(10/WIDTH_5S_SCALE);
        make.height.mas_offset(1);
        make.left.equalTo(weakSelf.phoneNumTextField);
        make.right.equalTo(weakSelf.view).mas_offset(-15/WIDTH_5S_SCALE);
    }];
    //密码图标
    [codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.left.equalTo(phoneImageView);
        make.top.equalTo(phoneImageView).mas_offset(50/WIDTH_5S_SCALE);
    }];
    //密码输入框
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(weakSelf.phoneNumTextField);
        make.centerY.equalTo(codeImageView.mas_centerY);
    }];
    //密码下横线
    [codeLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.left.equalTo(phoneLineView);
        make.top.equalTo(self.codeTextField.mas_bottom).mas_offset(10/WIDTH_5S_SCALE);
    }];
    // 登录CGRectMake(20 
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeLineView).mas_offset(30 / WIDTH_5S_SCALE);
        make.height.mas_offset(42 / HEIGHT_6S_SCALE);
        make.left.mas_offset(20 / WIDTH_6S_SCALE);
        make.right.mas_offset(-20 / WIDTH_6S_SCALE);
    }];
    //忘记密码
    [forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(loginBtn.mas_left);
        make.top.equalTo(loginBtn.mas_bottom).mas_offset(25/WIDTH_5S_SCALE);
        make.height.mas_equalTo(20/WIDTH_5S_SCALE);
    }];
    //快速注册
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(loginBtn.mas_right);
        make.height.bottom.equalTo(forgetBtn);
    }];
    //第三方登录标题
    [otherLogLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(registerBtn.mas_bottom).mas_offset(87/WIDTH_5S_SCALE);
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.height.mas_equalTo(20/WIDTH_5S_SCALE);
        make.width.mas_equalTo(74/WIDTH_5S_SCALE);
    }];
    //第三方登录横线
    [otherLogLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(otherLogLab.mas_centerY);
        make.height.mas_equalTo(1/WIDTH_5S_SCALE);
        make.left.right.equalTo(loginBtn);
    }];
    //微信头像
    [weChatImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(otherLogLab.mas_bottom).mas_offset(20/WIDTH_5S_SCALE);
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.width.height.mas_equalTo(44/WIDTH_5S_SCALE);
    }];
    //微信标题
    [weChatLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(30/WIDTH_5S_SCALE);
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.height.mas_offset(20/WIDTH_5S_SCALE);
        make.top.equalTo(weChatImageView.mas_bottom).mas_offset(7.5/WIDTH_5S_SCALE);
    }];
}
@end
